package com.bcx.wind.workflow.access;

import com.bcx.wind.workflow.exception.WorkflowException;
import com.bcx.wind.workflow.support.ResourceHelper;
import com.bcx.wind.workflow.support.StreamHelper;

import java.io.InputStream;
import java.sql.Connection;

import static com.bcx.wind.workflow.access.DbPro.*;
import static com.bcx.wind.workflow.support.ObjectHelper.hasValue;


/**
 * 数据库初始化
 *
 * @author zhanglei
 */
public final class DbInit  {

    public static final String DB_PATH = "com/bcx/wind/workflow/db/sql";

    public static String getDbSql(Connection connection){
        String sql = null;
        try {
            String productName = connection.getMetaData().getDatabaseProductName();
            String relName = productName.toLowerCase().replaceAll(" ","")
                    .replaceAll("_","");
            InputStream stream;

            if(hasValue(relName,DB2)){
                stream = ResourceHelper.getResourceAsStream(DB_PATH+"/DB2.sql");
                sql =  StreamHelper.getStr(stream);
            }else if(hasValue(relName,POSTGRESQL)){
                stream = ResourceHelper.getResourceAsStream(DB_PATH+"/postgres.sql");
                sql =  StreamHelper.getStr(stream);
            }else if(hasValue(relName,H2)){
                stream = ResourceHelper.getResourceAsStream(DB_PATH+"/H2.sql");
                sql =  StreamHelper.getStr(stream);
            }else if(hasValue(relName,ORACLE)){
                stream = ResourceHelper.getResourceAsStream(DB_PATH+"/Oracle.sql");
                sql =  StreamHelper.getStr(stream);
            }else if(hasValue(relName,MARIADB)){
                stream = ResourceHelper.getResourceAsStream(DB_PATH+"/MariaDB.sql");
                sql =  StreamHelper.getStr(stream);
            }else if(hasValue(relName,MYSQL)){
                stream = ResourceHelper.getResourceAsStream(DB_PATH+"/Mysql.sql");
                sql =  StreamHelper.getStr(stream);
            }else if(hasValue(relName,SQLSERVER)){
                stream = ResourceHelper.getResourceAsStream(DB_PATH+"/SqlServer.sql");
                sql =  StreamHelper.getStr(stream);
            }else{
                throw new WorkflowException("sorry! wind_workflow does not support this database for the time being: "+productName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new WorkflowException("sorry! get database name error ,because "+e.getMessage());
        }
        return sql;
    }

}
